package org.leafstar.shortlink.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.leafstar.shortlink.admin.common.biz.user.UserContext;
import org.leafstar.shortlink.admin.common.convention.exception.ClientException;
import org.leafstar.shortlink.admin.common.convention.result.Result;
import org.leafstar.shortlink.admin.dao.entity.GroupDo;
import org.leafstar.shortlink.admin.dao.mapper.GroupMapper;
import org.leafstar.shortlink.admin.dto.req.GroupSortReqDTO;
import org.leafstar.shortlink.admin.dto.req.GroupUpdateReqDTO;
import org.leafstar.shortlink.admin.dto.resp.GroupListRespDTO;
import org.leafstar.shortlink.admin.remote.dto.LinkRemoteService;
import org.leafstar.shortlink.admin.remote.dto.resp.LinkGroupCountQueryRespDTO;
import org.leafstar.shortlink.admin.service.GroupService;
import org.leafstar.shortlink.admin.util.BeanUtil;
import org.leafstar.shortlink.admin.util.RandomNumberGenerator;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 短链接分组Service层
 */
@Service
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDo> implements GroupService {

    @Override
    public void saveGroup(String groupName) {
        saveGroup(UserContext.getUsername(),groupName);
    }
    @Override
    public void saveGroup(String username, String groupName) {
        //如果gid存在则重新生成
        String gid;
        do {
            gid = RandomNumberGenerator.generateRandomNumber();
        } while (groupExist(gid, groupName));
        GroupDo groupDo = GroupDo.builder()
                .gid(gid)
                .sortOrder(0)
                .username(username)
                .name(groupName)
                .build();
        if (baseMapper.insert(groupDo) <= 0) {
            throw new ClientException("创建失败");
        }
//        return BeanUtil.convert(groupDo, GroupSaveRespDTO.class);
    }

    @Override
    public List<GroupListRespDTO> groupList() {
        LambdaUpdateWrapper<GroupDo> wrapper = new LambdaUpdateWrapper<GroupDo>()
                .eq(GroupDo::getUsername, UserContext.getUsername())
                .eq(GroupDo::getDelFlag, 0)
                .orderByDesc(GroupDo::getSortOrder)
                .orderByDesc(GroupDo::getUpdateTime);
        //多条件查询mp会报警告
        List<GroupDo> groups = baseMapper.selectList(wrapper);
        Result<List<LinkGroupCountQueryRespDTO>> result = LinkRemoteService.listGroupLinkCount(groups.stream().map(GroupDo::getGid).toList());
        List<GroupListRespDTO> groupList = BeanUtil.convert(groups, GroupListRespDTO.class);
        //gid:count
        List<LinkGroupCountQueryRespDTO> gidsToCount = result.getData();
        groupList.forEach(each -> {
            Optional<LinkGroupCountQueryRespDTO> first = gidsToCount.stream()
                    .filter(item -> Objects.equals(item.getGid(), each.getGid()))
                    .findFirst();
            first.ifPresent(item -> each.setShortLinkCount(first.get().getShortLinkCount()));
        });
        return groupList;
    }

    @Override
    public Boolean updateGroup(GroupUpdateReqDTO requestParam) {
        LambdaUpdateWrapper<GroupDo> updateWrapper = new LambdaUpdateWrapper<GroupDo>()
                .eq(GroupDo::getGid, requestParam.getGid())
                .eq(GroupDo::getUsername, UserContext.getUsername())
                .eq(GroupDo::getDelFlag, 0);
        //仅修改用户名
        int i = baseMapper.update(GroupDo.builder().name(requestParam.getName()).build(), updateWrapper);
        return i > 0;
    }

    @Override
    public Boolean deleteGroup(String gid) {
        LambdaUpdateWrapper<GroupDo> updateWrapper = new LambdaUpdateWrapper<GroupDo>()
                .eq(GroupDo::getGid, gid)
                .eq(GroupDo::getUsername, UserContext.getUsername())
                .eq(GroupDo::getDelFlag, 0);
        //进行逻辑删除
        GroupDo groupDo = new GroupDo();
        groupDo.setDelFlag(1);
        int i = baseMapper.update(groupDo, updateWrapper);
        return i > 0;
    }

    @Override
    public Boolean sortGroup(List<GroupSortReqDTO> requestParam) {
        requestParam.forEach(each -> {
            GroupDo groupDo = GroupDo.builder().sortOrder(each.getSort()).build();
            baseMapper.update(groupDo, new LambdaUpdateWrapper<GroupDo>()
                    .eq(GroupDo::getUsername, UserContext.getUsername())
                    .eq(GroupDo::getGid, each.getGid())
                    .eq(GroupDo::getDelFlag, 0));
        });
        return true;
    }

    private boolean groupExist(String gid, String username) {
        GroupDo groupDo = baseMapper.selectOne(new LambdaQueryWrapper<GroupDo>()
                .eq(GroupDo::getGid, gid)
                .eq(GroupDo::getUsername, Optional.ofNullable(username).orElse(UserContext.getUsername()))
        );
        return groupDo != null;
    }
}
